#include "UniversalProtocol.h"
#include <sstream>
#include <algorithm>
#include <chrono>

// 简化的JSON序列化实现（生产环境建议使用专业JSON库如nlohmann/json）
namespace JsonHelper 
{
    std::string escape(const std::string& str) 
    {
        std::string result;
        for (char c : str) 
        {
            switch (c) 
            {
                case '"': result += "\\\""; break;
                case '\\': result += "\\\\"; break;
                case '\n': result += "\\n"; break;
                case '\r': result += "\\r"; break;
                case '\t': result += "\\t"; break;
                default: result += c; break;
            }
        }
        return result;
    }
    
    std::string unescape(const std::string& str) 
    {
        std::string result;
        for (size_t i = 0; i < str.length(); ++i) 
        {
            if (str[i] == '\\' && i + 1 < str.length()) 
            {
                switch (str[i + 1]) 
                {
                    case '"': result += '"'; ++i; break;
                    case '\\': result += '\\'; ++i; break;
                    case 'n': result += '\n'; ++i; break;
                    case 'r': result += '\r'; ++i; break;
                    case 't': result += '\t'; ++i; break;
                    default: result += str[i]; break;
                }
            } 
            else 
            {
                result += str[i];
            }
        }
        return result;
    }
    
    // 简单的JSON值提取（仅用于演示，生产环境应使用专业库）
    std::string extractStringValue(const std::string& json, const std::string& key) 
    {
        std::string searchKey = "\"" + key + "\"";
        size_t pos = json.find(searchKey);
        if (pos == std::string::npos) return "";
        
        pos = json.find(':', pos);
        if (pos == std::string::npos) return "";
        
        pos = json.find('"', pos);
        if (pos == std::string::npos) return "";
        
        size_t start = pos + 1;
        size_t end = json.find('"', start);
        if (end == std::string::npos) return "";
        
        return unescape(json.substr(start, end - start));
    }
    
    uint32_t extractUintValue(const std::string& json, const std::string& key) 
    {
        std::string searchKey = "\"" + key + "\"";
        size_t pos = json.find(searchKey);
        if (pos == std::string::npos) return 0;
        
        pos = json.find(':', pos);
        if (pos == std::string::npos) return 0;
        
        // 跳过空白字符
        while (pos < json.length() && (json[pos] == ':' || json[pos] == ' ' || json[pos] == '\t')) 
        {
            pos++;
        }
        
        size_t end = pos;
        while (end < json.length() && std::isdigit(json[end])) 
        {
            end++;
        }
        
        if (end > pos) 
        {
            return static_cast<uint32_t>(std::stoul(json.substr(pos, end - pos)));
        }
        
        return 0;
    }
    
    double extractDoubleValue(const std::string& json, const std::string& key) 
    {
        std::string searchKey = "\"" + key + "\"";
        size_t pos = json.find(searchKey);
        if (pos == std::string::npos) return 0.0;
        
        pos = json.find(':', pos);
        if (pos == std::string::npos) return 0.0;
        
        while (pos < json.length() && (json[pos] == ':' || json[pos] == ' ' || json[pos] == '\t')) 
        {
            pos++;
        }
        
        size_t end = pos;
        while (end < json.length() && (std::isdigit(json[end]) || json[end] == '.')) 
        {
            end++;
        }
        
        if (end > pos) 
        {
            return std::stod(json.substr(pos, end - pos));
        }
        
        return 0.0;
    }
    
    bool extractBoolValue(const std::string& json, const std::string& key) 
    {
        std::string searchKey = "\"" + key + "\"";
        size_t pos = json.find(searchKey);
        if (pos == std::string::npos) return false;
        
        pos = json.find(':', pos);
        if (pos == std::string::npos) return false;
        
        return json.find("true", pos) != std::string::npos;
    }
}

namespace UniversalProtocol 
{
    // PlayerAttributes 实现
    std::string PlayerAttributes::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"level\":" << level << ","
            << "\"health\":" << health << ","
            << "\"maxHealth\":" << maxHealth << ","
            << "\"attackPower\":" << attackPower << ","
            << "\"defense\":" << defense << ","
            << "\"critChance\":" << critChance << ","
            << "\"critMultiplier\":" << critMultiplier << ","
            << "\"hitChance\":" << hitChance << ","
            << "\"dodgeChance\":" << dodgeChance << ","
            << "\"totalKills\":" << totalKills << ","
            << "\"gameState\":" << static_cast<uint8_t>(gameState) << ","
            << "\"isInAutoCombat\":" << (isInAutoCombat ? "true" : "false")
            << "}";
        return oss.str();
    }
    
    bool PlayerAttributes::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            level = JsonHelper::extractUintValue(jsonStr, "level");
            health = JsonHelper::extractUintValue(jsonStr, "health");
            maxHealth = JsonHelper::extractUintValue(jsonStr, "maxHealth");
            attackPower = JsonHelper::extractUintValue(jsonStr, "attackPower");
            defense = JsonHelper::extractUintValue(jsonStr, "defense");
            critChance = JsonHelper::extractUintValue(jsonStr, "critChance");
            critMultiplier = JsonHelper::extractDoubleValue(jsonStr, "critMultiplier");
            hitChance = JsonHelper::extractUintValue(jsonStr, "hitChance");
            dodgeChance = JsonHelper::extractUintValue(jsonStr, "dodgeChance");
            totalKills = JsonHelper::extractUintValue(jsonStr, "totalKills");
            gameState = static_cast<GameState>(JsonHelper::extractUintValue(jsonStr, "gameState"));
            isInAutoCombat = JsonHelper::extractBoolValue(jsonStr, "isInAutoCombat");
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // MonsterAttributes 实现
    std::string MonsterAttributes::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"level\":" << level << ","
            << "\"health\":" << health << ","
            << "\"maxHealth\":" << maxHealth << ","
            << "\"attackPower\":" << attackPower << ","
            << "\"defense\":" << defense << ","
            << "\"critChance\":" << critChance << ","
            << "\"critMultiplier\":" << critMultiplier << ","
            << "\"hitChance\":" << hitChance << ","
            << "\"dodgeChance\":" << dodgeChance << ","
            << "\"name\":\"" << JsonHelper::escape(name) << "\""
            << "}";
        return oss.str();
    }
    
    bool MonsterAttributes::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            level = JsonHelper::extractUintValue(jsonStr, "level");
            health = JsonHelper::extractUintValue(jsonStr, "health");
            maxHealth = JsonHelper::extractUintValue(jsonStr, "maxHealth");
            attackPower = JsonHelper::extractUintValue(jsonStr, "attackPower");
            defense = JsonHelper::extractUintValue(jsonStr, "defense");
            critChance = JsonHelper::extractUintValue(jsonStr, "critChance");
            critMultiplier = JsonHelper::extractDoubleValue(jsonStr, "critMultiplier");
            hitChance = JsonHelper::extractUintValue(jsonStr, "hitChance");
            dodgeChance = JsonHelper::extractUintValue(jsonStr, "dodgeChance");
            name = JsonHelper::extractStringValue(jsonStr, "name");
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // ClientInfo 实现
    std::string ClientInfo::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"clientType\":" << static_cast<uint8_t>(clientType) << ","
            << "\"clientName\":\"" << JsonHelper::escape(clientName) << "\","
            << "\"clientVersion\":\"" << JsonHelper::escape(clientVersion) << "\","
            << "\"protocolVersion\":{"
            << "\"major\":" << protocolVersion.major << ","
            << "\"minor\":" << protocolVersion.minor << ","
            << "\"patch\":" << protocolVersion.patch
            << "},"
            << "\"supportedFeatures\":[";
        
        for (size_t i = 0; i < supportedFeatures.size(); ++i) 
        {
            if (i > 0) oss << ",";
            oss << "\"" << JsonHelper::escape(supportedFeatures[i]) << "\"";
        }
        
        oss << "]}";
        return oss.str();
    }
    
    bool ClientInfo::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            clientType = static_cast<ClientType>(JsonHelper::extractUintValue(jsonStr, "clientType"));
            clientName = JsonHelper::extractStringValue(jsonStr, "clientName");
            clientVersion = JsonHelper::extractStringValue(jsonStr, "clientVersion");
            
            // 提取协议版本（简化实现）
            size_t protocolPos = jsonStr.find("\"protocolVersion\"");
            if (protocolPos != std::string::npos) 
            {
                protocolVersion.major = static_cast<uint16_t>(JsonHelper::extractUintValue(jsonStr, "major"));
                protocolVersion.minor = static_cast<uint16_t>(JsonHelper::extractUintValue(jsonStr, "minor"));
                protocolVersion.patch = static_cast<uint16_t>(JsonHelper::extractUintValue(jsonStr, "patch"));
            }
            
            // 注意：supportedFeatures的解析在简化实现中省略
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // HandshakeMessage 实现
    std::string HandshakeMessage::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"type\":" << static_cast<uint16_t>(type) << ","
            << "\"playerId\":" << playerId << ","
            << "\"timestamp\":" << timestamp << ","
            << "\"messageId\":" << messageId << ","
            << "\"clientInfo\":" << clientInfo.toJson()
            << "}";
        return oss.str();
    }
    
    bool HandshakeMessage::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            type = static_cast<MessageType>(JsonHelper::extractUintValue(jsonStr, "type"));
            playerId = JsonHelper::extractUintValue(jsonStr, "playerId");
            timestamp = static_cast<Timestamp>(JsonHelper::extractUintValue(jsonStr, "timestamp"));
            messageId = static_cast<MessageId>(JsonHelper::extractUintValue(jsonStr, "messageId"));
            
            // 提取clientInfo（简化实现）
            size_t infoPos = jsonStr.find("\"clientInfo\"");
            if (infoPos != std::string::npos) 
            {
                size_t start = jsonStr.find('{', infoPos);
                if (start != std::string::npos) 
                {
                    int braceCount = 1;
                    size_t end = start + 1;
                    while (end < jsonStr.length() && braceCount > 0) 
                    {
                        if (jsonStr[end] == '{') braceCount++;
                        else if (jsonStr[end] == '}') braceCount--;
                        end++;
                    }
                    if (braceCount == 0) 
                    {
                        std::string infoJson = jsonStr.substr(start, end - start);
                        clientInfo.fromJson(infoJson);
                    }
                }
            }
            
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // PlayerJoinMessage 实现
    std::string PlayerJoinMessage::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"type\":" << static_cast<uint16_t>(type) << ","
            << "\"playerId\":" << playerId << ","
            << "\"timestamp\":" << timestamp << ","
            << "\"messageId\":" << messageId << ","
            << "\"playerName\":\"" << JsonHelper::escape(playerName) << "\""
            << "}";
        return oss.str();
    }
    
    bool PlayerJoinMessage::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            type = static_cast<MessageType>(JsonHelper::extractUintValue(jsonStr, "type"));
            playerId = JsonHelper::extractUintValue(jsonStr, "playerId");
            timestamp = static_cast<Timestamp>(JsonHelper::extractUintValue(jsonStr, "timestamp"));
            messageId = static_cast<MessageId>(JsonHelper::extractUintValue(jsonStr, "messageId"));
            playerName = JsonHelper::extractStringValue(jsonStr, "playerName");
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // GameStatusMessage 实现
    std::string GameStatusMessage::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"type\":" << static_cast<uint16_t>(type) << ","
            << "\"playerId\":" << playerId << ","
            << "\"timestamp\":" << timestamp << ","
            << "\"messageId\":" << messageId << ","
            << "\"playerData\":" << playerData.toJson() << ","
            << "\"monsterData\":" << monsterData.toJson() << ","
            << "\"message\":\"" << JsonHelper::escape(message) << "\""
            << "}";
        return oss.str();
    }
    
    bool GameStatusMessage::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            type = static_cast<MessageType>(JsonHelper::extractUintValue(jsonStr, "type"));
            playerId = JsonHelper::extractUintValue(jsonStr, "playerId");
            timestamp = static_cast<Timestamp>(JsonHelper::extractUintValue(jsonStr, "timestamp"));
            messageId = static_cast<MessageId>(JsonHelper::extractUintValue(jsonStr, "messageId"));
            message = JsonHelper::extractStringValue(jsonStr, "message");
            
            // 解析嵌套的playerData和monsterData（简化实现）
            // 在生产环境中应使用专业的JSON解析库
            
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // CombatMessage 实现
    std::string CombatMessage::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"type\":" << static_cast<uint16_t>(type) << ","
            << "\"playerId\":" << playerId << ","
            << "\"timestamp\":" << timestamp << ","
            << "\"messageId\":" << messageId << ","
            << "\"message\":\"" << JsonHelper::escape(message) << "\""
            << "}";
        return oss.str();
    }
    
    bool CombatMessage::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            type = static_cast<MessageType>(JsonHelper::extractUintValue(jsonStr, "type"));
            playerId = JsonHelper::extractUintValue(jsonStr, "playerId");
            timestamp = static_cast<Timestamp>(JsonHelper::extractUintValue(jsonStr, "timestamp"));
            messageId = static_cast<MessageId>(JsonHelper::extractUintValue(jsonStr, "messageId"));
            message = JsonHelper::extractStringValue(jsonStr, "message");
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // LevelUpMessage 实现
    std::string LevelUpMessage::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"type\":" << static_cast<uint16_t>(type) << ","
            << "\"playerId\":" << playerId << ","
            << "\"timestamp\":" << timestamp << ","
            << "\"messageId\":" << messageId << ","
            << "\"newPlayerData\":" << newPlayerData.toJson() << ","
            << "\"message\":\"" << JsonHelper::escape(message) << "\""
            << "}";
        return oss.str();
    }
    
    bool LevelUpMessage::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            type = static_cast<MessageType>(JsonHelper::extractUintValue(jsonStr, "type"));
            playerId = JsonHelper::extractUintValue(jsonStr, "playerId");
            timestamp = static_cast<Timestamp>(JsonHelper::extractUintValue(jsonStr, "timestamp"));
            messageId = static_cast<MessageId>(JsonHelper::extractUintValue(jsonStr, "messageId"));
            message = JsonHelper::extractStringValue(jsonStr, "message");
            
            // newPlayerData解析（简化实现）
            
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // AttackMessage 实现
    std::string AttackMessage::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"type\":" << static_cast<uint16_t>(type) << ","
            << "\"playerId\":" << playerId << ","
            << "\"timestamp\":" << timestamp << ","
            << "\"messageId\":" << messageId << ","
            << "\"damage\":" << damage << ","
            << "\"targetHealth\":" << targetHealth << ","
            << "\"message\":\"" << JsonHelper::escape(message) << "\""
            << "}";
        return oss.str();
    }
    
    bool AttackMessage::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            type = static_cast<MessageType>(JsonHelper::extractUintValue(jsonStr, "type"));
            playerId = JsonHelper::extractUintValue(jsonStr, "playerId");
            timestamp = static_cast<Timestamp>(JsonHelper::extractUintValue(jsonStr, "timestamp"));
            messageId = static_cast<MessageId>(JsonHelper::extractUintValue(jsonStr, "messageId"));
            damage = JsonHelper::extractUintValue(jsonStr, "damage");
            targetHealth = JsonHelper::extractUintValue(jsonStr, "targetHealth");
            message = JsonHelper::extractStringValue(jsonStr, "message");
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // ErrorMessage 实现
    std::string ErrorMessage::toJson() const 
    {
        std::ostringstream oss;
        oss << "{"
            << "\"type\":" << static_cast<uint16_t>(type) << ","
            << "\"playerId\":" << playerId << ","
            << "\"timestamp\":" << timestamp << ","
            << "\"messageId\":" << messageId << ","
            << "\"errorCode\":" << errorCode << ","
            << "\"errorDescription\":\"" << JsonHelper::escape(errorDescription) << "\","
            << "\"originalMessageId\":" << originalMessageId
            << "}";
        return oss.str();
    }
    
    bool ErrorMessage::fromJson(const std::string& jsonStr) 
    {
        try 
        {
            type = static_cast<MessageType>(JsonHelper::extractUintValue(jsonStr, "type"));
            playerId = JsonHelper::extractUintValue(jsonStr, "playerId");
            timestamp = static_cast<Timestamp>(JsonHelper::extractUintValue(jsonStr, "timestamp"));
            messageId = static_cast<MessageId>(JsonHelper::extractUintValue(jsonStr, "messageId"));
            errorCode = JsonHelper::extractUintValue(jsonStr, "errorCode");
            errorDescription = JsonHelper::extractStringValue(jsonStr, "errorDescription");
            originalMessageId = static_cast<MessageId>(JsonHelper::extractUintValue(jsonStr, "originalMessageId"));
            return true;
        } 
        catch (...) 
        {
            return false;
        }
    }
    
    // MessageFactory 实现
    std::unique_ptr<UniversalMessage> MessageFactory::createFromJson(const std::string& jsonStr) 
    {
        try 
        {
            MessageType type = static_cast<MessageType>(JsonHelper::extractUintValue(jsonStr, "type"));
            return createFromType(type);
        } 
        catch (...) 
        {
            return nullptr;
        }
    }
    
    std::unique_ptr<UniversalMessage> MessageFactory::createFromType(MessageType type) 
    {
        switch (type) 
        {
            case MessageType::PROTOCOL_HANDSHAKE:
                return std::make_unique<HandshakeMessage>();
            case MessageType::PLAYER_JOIN:
                return std::make_unique<PlayerJoinMessage>();
            case MessageType::GAME_STATUS:
                return std::make_unique<GameStatusMessage>();
            case MessageType::COMBAT_MESSAGE:
                return std::make_unique<CombatMessage>();
            case MessageType::LEVEL_UP:
                return std::make_unique<LevelUpMessage>();
            case MessageType::ATTACK:
                return std::make_unique<AttackMessage>();
            case MessageType::ERROR_RESPONSE:
                return std::make_unique<ErrorMessage>();
            default:
                return nullptr;
        }
    }
    
    bool MessageFactory::isProtocolCompatible(const ProtocolVersion& clientVersion, const ProtocolVersion& serverVersion) 
    {
        // 主版本号必须相同，次版本号向下兼容
        if (clientVersion.major != serverVersion.major) 
        {
            return false;
        }
        
        // 客户端次版本号不能高于服务器
        if (clientVersion.minor > serverVersion.minor) 
        {
            return false;
        }
        
        return true;
    }
    
} // namespace UniversalProtocol 